/**
 * 报警分析模块
 */
(function () {
    // 全局变量
    let grainAlarmData = []; // 粮情报警数据
    let gasAlarmData = [];   // 气体报警数据
    let grainCurrentPage = 1;
    let gasCurrentPage = 1;
    const pageSize = 10;

    // 报警级别
    const ALARM_LEVELS = {
        HIGH: '高',
        MEDIUM: '中',
        LOW: '低'
    };

    // 报警状态
    const ALARM_STATUS = {
        ACTIVE: '未处理',
        HANDLED: '已处理',
        IGNORED: '已忽略'
    };

    // 初始化
    function init() {
        try {
            // 初始化Android接口
            if (typeof initAndroidInterface === 'function') {
                initAndroidInterface('报警分析');
            }
            bindEvents();
            initTabs();
            loadGrainAlarmData(); // 默认加载粮情报警数据
        } catch (error) {
            console.error('初始化报警分析模块失败:', error);
        }
    }

    // 绑定事件
    function bindEvents() {
        // 粮情报警刷新按钮
        const refreshGrainBtn = document.getElementById('refresh-grain-alarms');
        if (refreshGrainBtn) {
            refreshGrainBtn.addEventListener('click', function() {
                loadGrainAlarmData();
            });
        }

        // 气体报警刷新按钮
        const refreshGasBtn = document.getElementById('refresh-gas-alarms');
        if (refreshGasBtn) {
            refreshGasBtn.addEventListener('click', function() {
                loadGasAlarmData();
            });
        }

        // 粮情报警过滤器
        const grainTimeFilter = document.getElementById('grain-time-filter');
        const grainTypeFilter = document.getElementById('grain-type-filter');
        const grainLevelFilter = document.getElementById('grain-level-filter');

        if (grainTimeFilter) {
            grainTimeFilter.addEventListener('change', function() {
                loadGrainAlarmData();
            });
        }

        if (grainTypeFilter) {
            grainTypeFilter.addEventListener('change', function() {
                loadGrainAlarmData();
            });
        }

        if (grainLevelFilter) {
            grainLevelFilter.addEventListener('change', function() {
                loadGrainAlarmData();
            });
        }

        // 气体报警过滤器
        const gasTimeFilter = document.getElementById('gas-time-filter');
        const gasTypeFilter = document.getElementById('gas-type-filter');
        const gasLevelFilter = document.getElementById('gas-level-filter');

        if (gasTimeFilter) {
            gasTimeFilter.addEventListener('change', function() {
                loadGasAlarmData();
            });
        }

        if (gasTypeFilter) {
            gasTypeFilter.addEventListener('change', function() {
                loadGasAlarmData();
            });
        }

        if (gasLevelFilter) {
            gasLevelFilter.addEventListener('change', function() {
                loadGasAlarmData();
            });
        }
    }

    // 初始化选项卡
    function initTabs() {
        const tabItems = document.querySelectorAll('.tab-item');
        const tabContents = document.querySelectorAll('.tab-content');

        tabItems.forEach(tab => {
            tab.addEventListener('click', function() {
                const tabType = this.getAttribute('data-tab');
                
                // 切换选项卡样式
                tabItems.forEach(item => item.classList.remove('active'));
                this.classList.add('active');
                
                // 切换内容区域
                tabContents.forEach(content => {
                    content.style.display = 'none';
                });
                
                document.getElementById(`${tabType}-content`).style.display = 'block';
                
                // 加载对应数据
                if (tabType === 'grain') {
                    loadGrainAlarmData();
                } else if (tabType === 'gas') {
                    loadGasAlarmData();
                }
            });
        });
    }

    // 加载粮情报警数据
    function loadGrainAlarmData() {
        const timeFilter = document.getElementById('grain-time-filter').value;
        const typeFilter = document.getElementById('grain-type-filter').value;
        const levelFilter = document.getElementById('grain-level-filter').value;
        
        console.log('加载粮情报警数据:', {
            timeFilter,
            typeFilter,
            levelFilter,
            page: grainCurrentPage,
            pageSize
        });
        
        // 显示加载中
        const alarmListElement = document.getElementById('grain-alarm-list');
        if (!alarmListElement) return;
        
        alarmListElement.innerHTML = '<div class="loading-indicator">正在加载报警数据...</div>';
        
        // 检查是否应该使用模拟数据
        if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
            loadMockGrainAlarmData(timeFilter, typeFilter, levelFilter);
            return;
        }
        
        // 使用callAndroidMethodAsync获取报警列表
        if (typeof callAndroidMethodAsync === 'function') {
            const requestData = {
                timeRange: timeFilter,
                alarmType: typeFilter,
                alarmLevel: levelFilter,
                page: grainCurrentPage,
                pageSize: pageSize
            };
            
            callAndroidMethodAsync('getGrainAlarms', requestData)
                .then(response => {
                    if (response.success && response.data) {
                        grainAlarmData = Array.isArray(response.data) ? response.data :
                            (response.data.data ? response.data.data : []);
                        renderGrainAlarmList(grainAlarmData);
                        
                        // 更新总记录数和分页
                        const totalCount = response.data.totalCount || grainAlarmData.length;
                        const totalPages = Math.ceil(totalCount / pageSize);
                        updatePagination('grain-pagination', grainCurrentPage, totalPages, (page) => {
                            grainCurrentPage = page;
                            loadGrainAlarmData();
                        });
                        
                        // 更新总记录数显示
                        const totalCountElement = document.getElementById('grain-total-count');
                        if (totalCountElement) {
                            totalCountElement.textContent = totalCount;
                        }
                    } else {
                        console.error('获取粮情报警列表失败:', response.message);
                        showEmptyGrainAlarmList('获取报警数据失败: ' + (response.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('获取粮情报警列表异常:', error);
                    showEmptyGrainAlarmList('获取报警数据失败: ' + error.message);
                });
        } else {
            console.error('callAndroidMethodAsync 函数不可用');
            loadMockGrainAlarmData(timeFilter, typeFilter, levelFilter); // 回退到模拟数据
        }
    }

    // 加载气体报警数据
    function loadGasAlarmData() {
        const timeFilter = document.getElementById('gas-time-filter').value;
        const typeFilter = document.getElementById('gas-type-filter').value;
        const levelFilter = document.getElementById('gas-level-filter').value;
        
        console.log('加载气体报警数据:', {
            timeFilter,
            typeFilter,
            levelFilter,
            page: gasCurrentPage,
            pageSize
        });
        
        // 显示加载中
        const alarmListElement = document.getElementById('gas-alarm-list');
        if (!alarmListElement) return;
        
        alarmListElement.innerHTML = '<div class="loading-indicator">正在加载报警数据...</div>';
        
        // 检查是否应该使用模拟数据
        if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
            loadMockGasAlarmData(timeFilter, typeFilter, levelFilter);
            return;
        }
        
        // 使用callAndroidMethodAsync获取报警列表
        if (typeof callAndroidMethodAsync === 'function') {
            const requestData = {
                timeRange: timeFilter,
                gasType: typeFilter,
                alarmLevel: levelFilter,
                page: gasCurrentPage,
                pageSize: pageSize
            };
            
            callAndroidMethodAsync('getGasAlarms', requestData)
                .then(response => {
                    if (response.success && response.data) {
                        gasAlarmData = Array.isArray(response.data) ? response.data :
                            (response.data.data ? response.data.data : []);
                        renderGasAlarmList(gasAlarmData);
                        
                        // 更新总记录数和分页
                        const totalCount = response.data.totalCount || gasAlarmData.length;
                        const totalPages = Math.ceil(totalCount / pageSize);
                        updatePagination('gas-pagination', gasCurrentPage, totalPages, (page) => {
                            gasCurrentPage = page;
                            loadGasAlarmData();
                        });
                        
                        // 更新总记录数显示
                        const totalCountElement = document.getElementById('gas-total-count');
                        if (totalCountElement) {
                            totalCountElement.textContent = totalCount;
                        }
                    } else {
                        console.error('获取气体报警列表失败:', response.message);
                        showEmptyGasAlarmList('获取报警数据失败: ' + (response.message || '未知错误'));
                    }
                })
                .catch(error => {
                    console.error('获取气体报警列表异常:', error);
                    showEmptyGasAlarmList('获取报警数据失败: ' + error.message);
                });
        } else {
            console.error('callAndroidMethodAsync 函数不可用');
            loadMockGasAlarmData(timeFilter, typeFilter, levelFilter); // 回退到模拟数据
        }
    }
    
    // 加载模拟粮情报警数据
    function loadMockGrainAlarmData(timeFilter, typeFilter, levelFilter) {
        console.log('使用模拟粮情报警数据');
        
        // 模拟API延迟
        setTimeout(() => {
            // 使用AlarmAnalysisMockData获取模拟数据
            const response = AlarmAnalysisMockData.getGrainAlarms({
                timeRange: timeFilter,
                alarmType: typeFilter,
                alarmLevel: levelFilter,
                page: grainCurrentPage,
                pageSize: pageSize
            });
            
            // 处理响应
            if (response.success && response.data) {
                grainAlarmData = response.data.data;
                
                // 渲染数据
                renderGrainAlarmList(grainAlarmData);
                
                // 更新总记录数和分页
                const totalCount = response.data.totalCount;
                const totalPages = Math.ceil(totalCount / pageSize);
                
                updatePagination('grain-pagination', grainCurrentPage, totalPages, (page) => {
                    grainCurrentPage = page;
                    loadGrainAlarmData();
                });
                
                // 更新总记录数显示
                const totalCountElement = document.getElementById('grain-total-count');
                if (totalCountElement) {
                    totalCountElement.textContent = totalCount;
                }
            } else {
                console.error('获取粮情报警列表失败:', response.message);
                showEmptyGrainAlarmList('获取报警数据失败: ' + (response.message || '未知错误'));
            }
        }, 500);
    }
    
    // 显示空的粮情报警列表
    function showEmptyGrainAlarmList(message) {
        const alarmListElement = document.getElementById('grain-alarm-list');
        if (!alarmListElement) return;
        
        alarmListElement.innerHTML = `<div class="empty-list">${message || '暂无报警数据'}</div>`;
        
        // 更新总记录数显示
        const totalCountElement = document.getElementById('grain-total-count');
        if (totalCountElement) {
            totalCountElement.textContent = '0';
        }
        
        // 清空分页
        const paginationElement = document.getElementById('grain-pagination');
        if (paginationElement) {
            paginationElement.innerHTML = '';
        }
    }
    
    // 渲染粮情报警列表
    function renderGrainAlarmList(alarms) {
        const alarmListElement = document.getElementById('grain-alarm-list');
        if (!alarmListElement) return;
        
        if (!alarms || alarms.length === 0) {
            showEmptyGrainAlarmList();
            return;
        }
        
        // 创建表格
        const tableHTML = `
            <table class="device-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>测点位置</th>
                        <th>报警类型</th>
                        <th>实测值</th>
                        <th>阈值范围</th>
                        <th>报警级别</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${alarms.map(alarm => {
                        // 格式化级别和状态
                        const levelClass = alarm.level.toLowerCase();
                        const levelText = ALARM_LEVELS[alarm.level] || alarm.level;
                        
                        const statusClass = alarm.status.toLowerCase();
                        const statusText = ALARM_STATUS[alarm.status] || alarm.status;
                        
                        // 根据状态生成操作按钮
                        const actionButtons = alarm.status === 'ACTIVE' ?
                            `<button class="btn-view" data-id="${alarm.id}">查看</button>
                             <button class="btn-handle" data-id="${alarm.id}">处理</button>
                             <button class="btn-ignore" data-id="${alarm.id}">忽略</button>` :
                            `<button class="btn-view" data-id="${alarm.id}">查看</button>`;
                        
                        return `
                            <tr data-id="${alarm.id}">
                                <td>${alarm.time}</td>
                                <td>${alarm.location}</td>
                                <td>${alarm.type}</td>
                                <td>${alarm.value} ${alarm.unit}</td>
                                <td>${alarm.threshold}</td>
                                <td><span class="alarm-level ${levelClass}">${levelText}</span></td>
                                <td><span class="alarm-status ${statusClass}">${statusText}</span></td>
                                <td>${actionButtons}</td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        `;
        
        alarmListElement.innerHTML = tableHTML;
        
        // 绑定表格中的按钮事件
        bindGrainAlarmTableEvents();
    }
    
    // 绑定粮情报警表格中的按钮事件
    function bindGrainAlarmTableEvents() {
        // 查看按钮点击事件
        document.querySelectorAll('#grain-alarm-list .btn-view').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = grainAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    showGrainAlarmDetail(alarm);
                }
            });
        });
        
        // 处理按钮点击事件
        document.querySelectorAll('#grain-alarm-list .btn-handle').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = grainAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    handleGrainAlarm(alarm);
                }
            });
        });
        
        // 忽略按钮点击事件
        document.querySelectorAll('#grain-alarm-list .btn-ignore').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = grainAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    ignoreGrainAlarm(alarm);
                }
            });
        });
        
        // 行点击事件
        document.querySelectorAll('#grain-alarm-list .device-table tbody tr').forEach(row => {
            row.addEventListener('click', function(e) {
                // 如果点击的是按钮，则不触发行点击事件
                if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
                    return;
                }
                
                const alarmId = this.getAttribute('data-id');
                const alarm = grainAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    showGrainAlarmDetail(alarm);
                }
            });
        });
    }
    
    // 显示粮情报警详情
    function showGrainAlarmDetail(alarm) {
        if (typeof showFormModal !== 'function') {
            console.error('showFormModal 函数不可用');
            return;
        }
        
        const detailContent = `
            <div class="alarm-detail">
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">报警时间</div>
                        <div class="detail-value">${alarm.time}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">测点位置</div>
                        <div class="detail-value">${alarm.location}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">报警类型</div>
                        <div class="detail-value">${alarm.type}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">实测值</div>
                        <div class="detail-value">${alarm.value} ${alarm.unit}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">阈值范围</div>
                        <div class="detail-value">${alarm.threshold}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">报警级别</div>
                        <div class="detail-value">${ALARM_LEVELS[alarm.level] || alarm.level}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">报警状态</div>
                        <div class="detail-value">${ALARM_STATUS[alarm.status] || alarm.status}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">报警描述</div>
                        <div class="detail-value">${alarm.description || '无'}</div>
                    </div>
                </div>
            </div>
        `;
        
        showFormModal({
            title: '粮情报警详情',
            customContent: detailContent,
            fields: [],
            submitText: alarm.status === 'ACTIVE' ? '处理报警' : '关闭',
            cancelText: alarm.status === 'ACTIVE' ? '忽略报警' : '取消',
            onSubmit: function() {
                if (alarm.status === 'ACTIVE') {
                    handleGrainAlarm(alarm);
                }
            },
            onCancel: function() {
                if (alarm.status === 'ACTIVE') {
                    ignoreGrainAlarm(alarm);
                }
            }
        });
    }
    
    // 处理粮情报警
    function handleGrainAlarm(alarm) {
        if (typeof showConfirmDialog !== 'function') {
            console.error('showConfirmDialog 函数不可用');
            return;
        }
        
        showConfirmDialog({
            title: '处理报警',
            message: `确定要将报警 "${alarm.location} - ${alarm.type}" 标记为已处理吗？`,
            onConfirm: function() {
                // 检查是否应该使用模拟数据
                if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
                    // 使用AlarmAnalysisMockData处理报警
                    const response = AlarmAnalysisMockData.handleGrainAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功处理', 'success');
                        }
                        loadGrainAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                    return;
                }
                
                // 调用Android接口处理报警
                if (typeof callAndroidMethodAsync === 'function') {
                    callAndroidMethodAsync('handleGrainAlarm', { id: alarm.id })
                        .then(response => {
                            if (response.success) {
                                if (typeof showToast === 'function') {
                                    showToast('报警已成功处理', 'success');
                                }
                                loadGrainAlarmData(); // 重新加载数据
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('处理报警异常:', error);
                            if (typeof showToast === 'function') {
                                showToast('处理报警失败: ' + error.message, 'error');
                            }
                        });
                } else {
                    console.error('callAndroidMethodAsync 函数不可用');
                    // 使用AlarmAnalysisMockData处理报警
                    const response = AlarmAnalysisMockData.handleGrainAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功处理', 'success');
                        }
                        loadGrainAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                }
            }
        });
    }
    
    // 忽略粮情报警
    function ignoreGrainAlarm(alarm) {
        if (typeof showConfirmDialog !== 'function') {
            console.error('showConfirmDialog 函数不可用');
            return;
        }
        
        showConfirmDialog({
            title: '忽略报警',
            message: `确定要将报警 "${alarm.location} - ${alarm.type}" 标记为已忽略吗？`,
            onConfirm: function() {
                // 检查是否应该使用模拟数据
                if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
                    // 使用AlarmAnalysisMockData忽略报警
                    const response = AlarmAnalysisMockData.ignoreGrainAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功忽略', 'success');
                        }
                        loadGrainAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                    return;
                }
                
                // 调用Android接口忽略报警
                if (typeof callAndroidMethodAsync === 'function') {
                    callAndroidMethodAsync('ignoreGrainAlarm', { id: alarm.id })
                        .then(response => {
                            if (response.success) {
                                if (typeof showToast === 'function') {
                                    showToast('报警已成功忽略', 'success');
                                }
                                loadGrainAlarmData(); // 重新加载数据
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('忽略报警异常:', error);
                            if (typeof showToast === 'function') {
                                showToast('忽略报警失败: ' + error.message, 'error');
                            }
                        });
                } else {
                    console.error('callAndroidMethodAsync 函数不可用');
                    // 使用AlarmAnalysisMockData忽略报警
                    const response = AlarmAnalysisMockData.ignoreGrainAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功忽略', 'success');
                        }
                        loadGrainAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                }
            }
        }); 
    }
    
    // 更新分页
    function updatePagination(containerId, currentPage, totalPages, onPageChange) {
        const container = document.getElementById(containerId);
        if (!container) return;
        
        // 清空容器
        container.innerHTML = '';
        
        if (totalPages <= 1) {
            return; // 只有一页或没有数据，不显示分页
        }
        
        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = 'pagination-btn';
        prevBtn.innerHTML = '<i class="layui-icon layui-icon-left"></i> 上一页';
        prevBtn.disabled = currentPage <= 1;
        if (currentPage > 1) {
            prevBtn.addEventListener('click', function() {
                onPageChange(currentPage - 1);
            });
        }
        container.appendChild(prevBtn);
        
        // 页码按钮
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, startPage + 4);
        
        if (endPage - startPage < 4) {
            startPage = Math.max(1, endPage - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'pagination-btn' + (i === currentPage ? ' active' : '');
            pageBtn.textContent = i;
            
            if (i !== currentPage) {
                pageBtn.addEventListener('click', function() {
                    onPageChange(i);
                });
            }
            
            container.appendChild(pageBtn);
        }
        
        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = 'pagination-btn';
        nextBtn.innerHTML = '下一页 <i class="layui-icon layui-icon-right"></i>';
        nextBtn.disabled = currentPage >= totalPages;
        if (currentPage < totalPages) {
            nextBtn.addEventListener('click', function() {
                onPageChange(currentPage + 1);
            });
        }
        container.appendChild(nextBtn);
    }

    // 暴露公共方法到全局
    window.AlarmAnalysis = {
        init
    };

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        init();
    });
    
    // 加载模拟气体报警数据
    function loadMockGasAlarmData(timeFilter, typeFilter, levelFilter) {
        console.log('使用模拟气体报警数据');
        
        // 模拟API延迟
        setTimeout(() => {
            // 使用AlarmAnalysisMockData获取模拟数据
            const response = AlarmAnalysisMockData.getGasAlarms({
                timeRange: timeFilter,
                gasType: typeFilter,
                alarmLevel: levelFilter,
                page: gasCurrentPage,
                pageSize: pageSize
            });
            
            // 处理响应
            if (response.success && response.data) {
                gasAlarmData = response.data.data;
                
                // 渲染数据
                renderGasAlarmList(gasAlarmData);
                
                // 更新总记录数和分页
                const totalCount = response.data.totalCount;
                const totalPages = Math.ceil(totalCount / pageSize);
                
                updatePagination('gas-pagination', gasCurrentPage, totalPages, (page) => {
                    gasCurrentPage = page;
                    loadGasAlarmData();
                });
                
                // 更新总记录数显示
                const totalCountElement = document.getElementById('gas-total-count');
                if (totalCountElement) {
                    totalCountElement.textContent = totalCount;
                }
            } else {
                console.error('获取气体报警列表失败:', response.message);
                showEmptyGasAlarmList('获取报警数据失败: ' + (response.message || '未知错误'));
            }
        }, 500);
    }
    
    // 显示空的气体报警列表
    function showEmptyGasAlarmList(message) {
        const alarmListElement = document.getElementById('gas-alarm-list');
        if (!alarmListElement) return;
        
        alarmListElement.innerHTML = `<div class="empty-list">${message || '暂无报警数据'}</div>`;
        
        // 更新总记录数显示
        const totalCountElement = document.getElementById('gas-total-count');
        if (totalCountElement) {
            totalCountElement.textContent = '0';
        }
        
        // 清空分页
        const paginationElement = document.getElementById('gas-pagination');
        if (paginationElement) {
            paginationElement.innerHTML = '';
        }
    }
    
    // 渲染气体报警列表
    function renderGasAlarmList(alarms) {
        const alarmListElement = document.getElementById('gas-alarm-list');
        if (!alarmListElement) return;
        
        if (!alarms || alarms.length === 0) {
            showEmptyGasAlarmList();
            return;
        }
        
        // 创建表格
        const tableHTML = `
            <table class="device-table">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>测点位置</th>
                        <th>气体类型</th>
                        <th>实测值</th>
                        <th>阈值范围</th>
                        <th>报警级别</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${alarms.map(alarm => {
                        // 格式化级别和状态
                        const levelClass = alarm.level.toLowerCase();
                        const levelText = ALARM_LEVELS[alarm.level] || alarm.level;
                        
                        const statusClass = alarm.status.toLowerCase();
                        const statusText = ALARM_STATUS[alarm.status] || alarm.status;
                        
                        // 根据状态生成操作按钮
                        const actionButtons = alarm.status === 'ACTIVE' ?
                            `<button class="btn-view" data-id="${alarm.id}">查看</button>
                             <button class="btn-handle" data-id="${alarm.id}">处理</button>
                             <button class="btn-ignore" data-id="${alarm.id}">忽略</button>` :
                            `<button class="btn-view" data-id="${alarm.id}">查看</button>`;
                        
                        return `
                            <tr data-id="${alarm.id}">
                                <td>${alarm.time}</td>
                                <td>${alarm.location}</td>
                                <td>${alarm.type}</td>
                                <td>${alarm.value} ${alarm.unit}</td>
                                <td>${alarm.threshold}</td>
                                <td><span class="alarm-level ${levelClass}">${levelText}</span></td>
                                <td><span class="alarm-status ${statusClass}">${statusText}</span></td>
                                <td>${actionButtons}</td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        `;
        
        alarmListElement.innerHTML = tableHTML;
        
        // 绑定表格中的按钮事件
        bindGasAlarmTableEvents();
    }
    
    // 绑定气体报警表格中的按钮事件
    function bindGasAlarmTableEvents() {
        // 查看按钮点击事件
        document.querySelectorAll('#gas-alarm-list .btn-view').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = gasAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    showGasAlarmDetail(alarm);
                }
            });
        });
        
        // 处理按钮点击事件
        document.querySelectorAll('#gas-alarm-list .btn-handle').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = gasAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    handleGasAlarm(alarm);
                }
            });
        });
        
        // 忽略按钮点击事件
        document.querySelectorAll('#gas-alarm-list .btn-ignore').forEach(button => {
            button.addEventListener('click', function(e) {
                e.stopPropagation();
                const alarmId = this.getAttribute('data-id');
                const alarm = gasAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    ignoreGasAlarm(alarm);
                }
            });
        });
        
        // 行点击事件
        document.querySelectorAll('#gas-alarm-list .device-table tbody tr').forEach(row => {
            row.addEventListener('click', function(e) {
                // 如果点击的是按钮，则不触发行点击事件
                if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
                    return;
                }
                
                const alarmId = this.getAttribute('data-id');
                const alarm = gasAlarmData.find(a => a.id == alarmId);
                if (alarm) {
                    showGasAlarmDetail(alarm);
                }
            });
        });
    }
    
    // 显示气体报警详情
    function showGasAlarmDetail(alarm) {
        if (typeof showFormModal !== 'function') {
            console.error('showFormModal 函数不可用');
            return;
        }
        
        const detailContent = `
            <div class="alarm-detail">
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">报警时间</div>
                        <div class="detail-value">${alarm.time}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">测点位置</div>
                        <div class="detail-value">${alarm.location}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">气体类型</div>
                        <div class="detail-value">${alarm.type}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">实测值</div>
                        <div class="detail-value">${alarm.value} ${alarm.unit}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">阈值范围</div>
                        <div class="detail-value">${alarm.threshold}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">报警级别</div>
                        <div class="detail-value">${ALARM_LEVELS[alarm.level] || alarm.level}</div>
                    </div>
                </div>
                <div class="detail-row">
                    <div class="detail-item">
                        <div class="detail-label">报警状态</div>
                        <div class="detail-value">${ALARM_STATUS[alarm.status] || alarm.status}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">报警描述</div>
                        <div class="detail-value">${alarm.description || '无'}</div>
                    </div>
                </div>
            </div>
        `;
        
        showFormModal({
            title: '气体报警详情',
            customContent: detailContent,
            fields: [],
            submitText: alarm.status === 'ACTIVE' ? '处理报警' : '关闭',
            cancelText: alarm.status === 'ACTIVE' ? '忽略报警' : '取消',
            onSubmit: function() {
                if (alarm.status === 'ACTIVE') {
                    handleGasAlarm(alarm);
                }
            },
            onCancel: function() {
                if (alarm.status === 'ACTIVE') {
                    ignoreGasAlarm(alarm);
                }
            }
        });
    }
    
    // 处理气体报警
    function handleGasAlarm(alarm) {
        if (typeof showConfirmDialog !== 'function') {
            console.error('showConfirmDialog 函数不可用');
            return;
        }
        
        showConfirmDialog({
            title: '处理报警',
            message: `确定要将报警 "${alarm.location} - ${alarm.type}" 标记为已处理吗？`,
            onConfirm: function() {
                // 检查是否应该使用模拟数据
                if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
                    // 使用AlarmAnalysisMockData处理报警
                    const response = AlarmAnalysisMockData.handleGasAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功处理', 'success');
                        }
                        loadGasAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                    return;
                }
                
                // 调用Android接口处理报警
                if (typeof callAndroidMethodAsync === 'function') {
                    callAndroidMethodAsync('handleGasAlarm', { id: alarm.id })
                        .then(response => {
                            if (response.success) {
                                if (typeof showToast === 'function') {
                                    showToast('报警已成功处理', 'success');
                                }
                                loadGasAlarmData(); // 重新加载数据
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('处理报警异常:', error);
                            if (typeof showToast === 'function') {
                                showToast('处理报警失败: ' + error.message, 'error');
                            }
                        });
                } else {
                    console.error('callAndroidMethodAsync 函数不可用');
                    // 使用AlarmAnalysisMockData处理报警
                    const response = AlarmAnalysisMockData.handleGasAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功处理', 'success');
                        }
                        loadGasAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('处理报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                }
            }
        });
    }
    
    // 忽略气体报警
    function ignoreGasAlarm(alarm) {
        if (typeof showConfirmDialog !== 'function') {
            console.error('showConfirmDialog 函数不可用');
            return;
        }
        
        showConfirmDialog({
            title: '忽略报警',
            message: `确定要将报警 "${alarm.location} - ${alarm.type}" 标记为已忽略吗？`,
            onConfirm: function() {
                // 检查是否应该使用模拟数据
                if (typeof shouldUseMockData === 'function' && shouldUseMockData()) {
                    // 使用AlarmAnalysisMockData忽略报警
                    const response = AlarmAnalysisMockData.ignoreGasAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功忽略', 'success');
                        }
                        loadGasAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                    return;
                }
                
                // 调用Android接口忽略报警
                if (typeof callAndroidMethodAsync === 'function') {
                    callAndroidMethodAsync('ignoreGasAlarm', { id: alarm.id })
                        .then(response => {
                            if (response.success) {
                                if (typeof showToast === 'function') {
                                    showToast('报警已成功忽略', 'success');
                                }
                                loadGasAlarmData(); // 重新加载数据
                            } else {
                                if (typeof showToast === 'function') {
                                    showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                                }
                            }
                        })
                        .catch(error => {
                            console.error('忽略报警异常:', error);
                            if (typeof showToast === 'function') {
                                showToast('忽略报警失败: ' + error.message, 'error');
                            }
                        });
                } else {
                    console.error('callAndroidMethodAsync 函数不可用');
                    // 使用AlarmAnalysisMockData忽略报警
                    const response = AlarmAnalysisMockData.ignoreGasAlarm({ id: alarm.id });
                    
                    if (response.success) {
                        if (typeof showToast === 'function') {
                            showToast('报警已成功忽略', 'success');
                        }
                        loadGasAlarmData(); // 重新加载数据
                    } else {
                        if (typeof showToast === 'function') {
                            showToast('忽略报警失败: ' + (response.message || '未知错误'), 'error');
                        }
                    }
                }
            }
        }); 
    }
})(); 